package cn.com.ccxe.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.ccxe.core.entity.ArticlePaging;
import cn.com.ccxe.core.search.FullTextSearch;
import cn.com.ccxe.core.search.SearchTerm;
import cn.com.ccxe.web.form.SearchActionForm;

import com.ccxe.manage.service.CurrUserInfo;

public class SearchAction extends BasciAction {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(SearchAction.class);
	
	@Override
	protected void dispatch(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.info("--------MonitorTypeAction.dispatch()------");
		SearchActionForm actionForm = new SearchActionForm(req);
		//请求的方法
		String method = actionForm.getMethod();
		if(isEmpty(method)) {
			method = method.trim();
		}
		CurrUserInfo userInfo = actionForm.getUserInfo();
		if(userInfo == null) {
			logger.info("用户信息已过期，请重新登录！");
			resp.sendRedirect("/login.jsp");
			invalidateSession(req);
			return;
		}
		else if(!isEmpty(method)) {
			show(req, resp, actionForm);
		}
		else if("show".equals(method)) {
			show(req, resp, actionForm);
		}
		else if("search".equals(method)) {
			search(req, resp, actionForm);
		}
	}
	
	private boolean isEmpty(String method) {
		return !StringUtils.isEmpty(method);
	}

	private void show(HttpServletRequest req,
				 HttpServletResponse resp, 
				 SearchActionForm actionForm)
			throws ServletException,
				   IOException {
		redirect(req, resp, "/zebra/customer/search/show.jsp");
	}
	
	private void search(HttpServletRequest req,
									HttpServletResponse resp, 
									SearchActionForm actionForm)
			throws ServletException,
				   IOException {
		SearchTerm term = appendSearchTerm(actionForm);
		int requestPage = actionForm.getRequestPage();
		
		FullTextSearch fts = new FullTextSearch();
		ArticlePaging paging =  fts.search(term, requestPage*22, (requestPage+1)*22);

		req.setAttribute("currentPage", requestPage);
		req.setAttribute("paging", paging);
		req.setAttribute("term",term);
		forward(req, resp, "/zebra/customer/search/dataList.jsp");
	}

	private SearchTerm appendSearchTerm(SearchActionForm form) {
		SearchTerm term = new SearchTerm();
		term.setKeyword(form.getKeyword());
		term.setBeginDate(form.getBeginDate());
		term.setEndDate(form.getEndDate());
		term.setIsSearchContent(form.getIsSearchContent());
		return term;
	}
	
}
